# -*- coding: utf-8 -*-

from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from scrapy.http.response.html import HtmlResponse
from selenium.webdriver.common.by import By
from selenium import webdriver
from scrapy import signals
import win32con
import win32api
import time

class SeleniumDownloaderMiddleware(object):
    def __init__(self):
        self.webdriver = webdriver.Chrome(executable_path=r'D:\chrome\Google\Chrome\Application\chromedriver')

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        pass


    def process_response(self, request, response, spider):
        if request.url == 'https://cd.fang.com/':
            self.webdriver.get(request.url)
            wait = WebDriverWait(self.webdriver,timeout=10)
            wait.until(ec.visibility_of_element_located((By.XPATH,'//*[@id="dsy_H01_03"]/div[1]//a'))).click()
            source = self.webdriver.page_source
            response = HtmlResponse(url=self.webdriver.current_url, body=source, encoding='utf-8', request=request)

            return response
        else:
            VK_CODE = {'enter': 0x0D, 'down_arrow': 0x28}

            def keyDown(keyName):
                win32api.keybd_event(VK_CODE[keyName], 0, 0, 0)

            def keyUp(keyName):
                win32api.keybd_event(VK_CODE[keyName], 0, win32con.KEYEVENTF_KEYUP, 0)

            self.webdriver.get(
                request.url)

            image = self.webdriver.find_element_by_xpath('//*[@style="-webkit-user-select: none;margin: auto;"]')
            action = ActionChains(self.webdriver).move_to_element(image)

            action.context_click(image).perform()
            time.sleep(1)

            win32api.keybd_event(86, 0, 0, 0)
            win32api.keybd_event(86, 0, win32con.KEYEVENTF_KEYUP, 0)
            time.sleep(1)

            keyDown('enter')
            keyUp('enter')
            time.sleep(1)


    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)
